//
//  XDLoginViewController.m
//  XDEducation
//
//  Created by apple on 2017/4/3.
//  Copyright © 2017年 apple. All rights reserved.
//

#import "XDLoginViewController.h"

#import "XDRegisterViewController.h"
#import "XDLoginHeaderView.h"
#import "XDLoginTextFieldCell.h"
#import "XDLoginBtnCell.h"
#import "XDForgetPwddViewController.h"
#import "XDTabBarController.h"
#import "ADView.h"

@interface XDLoginViewController ()<UITextFieldDelegate>
{
    NSString *_account;     //用户名
    NSString *_password;    //密码
    Account *_accountInfo;  //用户信息
    
    
}

/** username textfield */
@property(nonatomic,strong) UITextField *usernameTextField;

/** password */
@property(nonatomic,strong) UITextField *passwordTextField;
@end

#define UsernameKey @"username"
#define PasswordKey @"password"

static NSString *const cellId = @"LoginCell";

@implementation XDLoginViewController

- (void)viewDidLoad {
    
    [super viewDidLoad];
    [ADView initLaunchAds];

    [self initTableView];
}


/**
 初始化tableView
 */
-(void)initTableView{

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.tableView.backgroundColor = [UIColor whiteColor];
    self.tableView.scrollEnabled = NO;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(returnKeyboard)];
    [self.tableView addGestureRecognizer:tap];
}

#pragma - mark tableView delegate

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{

    return 1;
}


-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{

    return 3;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSString *currentUsername = [[NSUserDefaults standardUserDefaults]objectForKey:UsernameKey];
    NSString *currentPassword = [[NSUserDefaults standardUserDefaults]objectForKey:PasswordKey];
    
    WeakSelf(weakself)
    switch (indexPath.row) {
        case 0:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"login_icon_user" title:@"账    号:" textFieldPalceHolder:@"请输入用户名/手机号" tableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            self.usernameTextField = cell.textField;
            self.usernameTextField.delegate = self;
            self.usernameTextField.text = currentUsername;
            _account = currentUsername;
            return cell;
        }
            break;
           
        case 1:{
            
            XDLoginTextFieldCell *cell = [XDLoginTextFieldCell cellImageName:@"login_icon_password" title:@"密    码:" textFieldPalceHolder:@"请输入密码" tableView:tableView];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
            cell.hidePassword = YES;
            self.passwordTextField = cell.textField;
            self.passwordTextField.delegate = self;
            self.passwordTextField.text = currentPassword;
            _password = currentPassword;
            return cell;
        
        }
        case 2:{
            XDLoginBtnCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            if (!cell) {
                [tableView registerNib:[UINib nibWithNibName:@"XDLoginBtnCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:cellId];
                cell = [tableView dequeueReusableCellWithIdentifier:cellId];
            }
            //注册block
            cell.registerBlock = ^(){
                [weakself registerEvent];
            };
            //忘记密码
            cell.forgetPwdBlock = ^(){
                [weakself forgetPasswordEvent];
            };
            //登录
            cell.loginBlock = ^(){
                [weakself loginEvent];
            };
            return cell;
            
        }
        default:
            return nil;
            break;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if(indexPath.row == 2) return 135 * ScaleHeight ;
    return 70 * ScaleHeight;
}

-(UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    XDLoginHeaderView *headerView = [[XDLoginHeaderView alloc]init];
    
    //返回block
    WeakSelf(weakself)
    headerView.backBlock = ^(){
        
        [weakself dismissViewControllerAnimated:YES completion:nil];
    };
    //注册block
    
    headerView.registerBlock = ^(){
        [weakself registerEvent];
    };
    return headerView;
}

-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{

    return (ScreenH/3 + 40 ) * ScaleHeight;
}


#pragma mark - 处理事件


/** 登录 */
-(void)loginEvent{
    
    //退出键盘
    [self returnKeyboard];
    
    if(_account.length < 6){
        [MBProgressHUD showError:@"请输入正确的用户名"];
        return;
    }
    
    //处理 账号密码 逻辑
    if (_password.length < 6) {
        [MBProgressHUD showError:@"请输入正确的密码"];
        return;
    }
    
    [MBProgressHUD showMessage:@"正在登录"];
    //请求参数
    NSDictionary *dict = @{@"phone":_account,@"password":_password};
    
    [XDHttpTool get:BaseURL(@"user.do?action=login2") params:dict success:^(id responseObj) {
        
        NSLog(@"%@",responseObj);
        //登录提示
        NSString *message = [responseObj objectForKey:@"msg"];
        [MBProgressHUD showSuccess:message];
        
        if ([[responseObj objectForKey:@"code"] integerValue ] == 1000) {
            
            NSDictionary *dict = [responseObj objectForKey:@"t"];
            
            //保存账号信息
            _accountInfo = [[Account alloc] init];
            
            NSString *uid = [[dict objectForKey:@"uid"]stringValue];
            NSString *userName = [dict objectForKey:@"username"];
            NSString *petName = [dict objectForKey:@"petName"];
            NSString *iconUrl = [dict objectForKey:@"avatar"];
            NSString *rolecode = [dict objectForKey:@"rolecode"];
            NSNumber *invite_uid = [dict objectForKey:@"invite_uid"];
            NSString *avatar = [dict objectForKey:@"avatar"];
            NSNumber *executeUid = [dict objectForKey:@"executeUid"];
            
            _accountInfo.uid = uid;
            _accountInfo.username = userName;
            _accountInfo.petName = petName;
            _accountInfo.headImageUrl = iconUrl;
            _accountInfo.rolecode = rolecode;
            _accountInfo.invite_uid = invite_uid;
            _accountInfo.avatar = avatar;
            _accountInfo.executeUid = executeUid;
            
            NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
            [defaults setObject:[dict objectForKey:@"rolecode"] forKey:@"rolecode"];
            [defaults synchronize];
            
            //地域
            NSString *city = [[dict objectForKey:@"city"] objectForKey:@"cityname"];
            NSString *province = [[dict objectForKey:@"province"] objectForKey:@"provincename"];
            _accountInfo.area = [NSString stringWithFormat:@"%@%@",province,city];
            
            
            [[AccountTool shareAccountTool] saveAccount:_accountInfo];
            
            //存储账号密码
            [[NSUserDefaults standardUserDefaults] setObject:_account forKey:UsernameKey];
            [[NSUserDefaults standardUserDefaults] setObject:_password forKey:PasswordKey];
            
            //auth加密
            [self authEncryptWithUserName:_account password:_password];
            
        }else{
        
            //登录失败
        }

  
    } failure:^(NSError *error) {
        
        NSLog(@"%@",error);
    }];
}


//auth加密
-(void)authEncryptWithUserName:(NSString *)userName password:(NSString *)password{
    
    NSString *source = [NSString stringWithFormat:@"%@:%@",userName,password];
    
    NSString *url = [NSString stringWithFormat:@"auth.do?action=genAuthCode&source=%@&key=keykeyString",source];
    
    [XDHttpTool get:BaseURL(url) success:^(id responseObj) {
        
        NSLog(@"%@",responseObj);
        
        NSDictionary *dict = [responseObj objectForKey:@"t"];
        
        NSString *auth = [dict objectForKey:@"authCode"];
        
        //保存auth信息
        
        _accountInfo.authCode = auth;
        [[AccountTool shareAccountTool] saveAccount:_accountInfo];
       
        
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        [defaults setObject:auth forKey:@"authCode"];
        [defaults synchronize];
        
        
        
        
        //切换根控制器
        XDTabBarController *vc = [[XDTabBarController alloc]init];
        [UIApplication sharedApplication].keyWindow.rootViewController = vc;
        
        
        CATransition *animation = [CATransition animation];
        
        [animation setDuration:0.6];//设置动画时间
        
        animation.type = kCATransitionFade;//设置动画类型
        
        [[UIApplication sharedApplication].keyWindow.layer addAnimation:animation forKey:nil];

        
    } failure:^(NSError *error) {
        
        [MBProgressHUD  showError:@"获取auth加密失败"];
    }];
    
}

/** 注册 */
-(void)registerEvent{
    
    [self returnKeyboard];
    
    XDRegisterViewController *vc = [[XDRegisterViewController alloc]init];
    [self presentViewController:vc animated:YES completion:nil];
}

/** 忘记密码 */
-(void)forgetPasswordEvent{

    [self returnKeyboard];
    
    XDForgetPwddViewController *vc = [[XDForgetPwddViewController alloc]init];
    
    [self presentViewController:vc animated:YES completion:nil];
    
}


/** 退出键盘 */
-(void)returnKeyboard{

    [self.view endEditing:YES];
}

//弹回键盘
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    
    
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y - 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}

//在UITextField 编辑完成调用方法
- (void)textFieldDidEndEditing:(UITextField *)textField
{
    
    if (textField == self.usernameTextField) {
        _account = textField.text;
    }else{
        _password = textField.text;
    }
    
    //设置动画的名字
    [UIView beginAnimations:@"Animation" context:nil];
    //设置动画的间隔时间
    [UIView setAnimationDuration:0.20];
    //??使用当前正在运行的状态开始下一段动画
    [UIView setAnimationBeginsFromCurrentState: YES];
    //设置视图移动的位移
    self.view.frame = CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y + 100, self.view.frame.size.width, self.view.frame.size.height);
    //设置动画结束
    [UIView commitAnimations];
}


-(void)dealloc
{
    NSLog(@"%s",__func__);
}
@end
